package com.xh.sys.config;

import com.xh.common.Err;
import com.xh.common.ExceptionEnum;
import com.xh.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Err.BusinessException.class)
    @ResponseBody
    public R<Err.BusinessExceptionOut> handleException(Err.BusinessException e) {
        log.info("Err.BusinessException:{}", e.getCode());
        Err.BusinessExceptionOut build = Err.BusinessExceptionOut.builder()
                .code(e.getCode())
                .msg(e.getMsg())
                .build();
        R<Err.BusinessExceptionOut> failed = R.failed(e.getMsg(), build);
        return failed;
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R<Err.BusinessExceptionOut> handleException(BindException e) {
        log.info("Err.BusinessException:{}", e.getAllErrors());
        Err.BusinessExceptionOut build = Err.BusinessExceptionOut.builder()
                .code(ExceptionEnum.BAD_REQUEST.getCode() + "")
                .msg(e.getAllErrors().get(0).getDefaultMessage())
                .build();
        R<Err.BusinessExceptionOut> failed = R.failed("参数校验问题", build);
        return failed;
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public R<Err.BusinessExceptionOut> handleException(ConstraintViolationException e) {
        log.info("Err.BusinessException:{}", e.getMessage());
        Err.BusinessExceptionOut build = Err.BusinessExceptionOut.builder()
                .code(ExceptionEnum.BAD_REQUEST.getCode() + "")
                .msg(e.getConstraintViolations().iterator().next().getMessage())
                .build();
        R<Err.BusinessExceptionOut> failed = R.failed("参数校验问题", build);
        return failed;
    }

}
